<template>
  <!-- 搜索框 -->
  <el-card style="height: 80px">
    <el-form :model="queryForm" :inline="true" class="form">
      <el-form-item label="名称:">
        <el-input
            v-model="queryForm.queryName"
            placeholder="请输入名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select
            v-model="queryForm.queryStatus"
            placeholder="请选择状态"
            style="width: 200px"
            clearable
        >
          <el-option label="全部" :value="0"></el-option>
          <el-option label="营业中" :value="1"></el-option>
          <el-option label="已打烊" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search">
          搜索
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 添加用户和批量删除 -->
  <el-card style="margin: 10px 0">
    <el-tooltip effect="dark" content="添加" placement="top">
      <el-button type="success" size="default" icon="Plus" @click="handleAdd">
      </el-button>
    </el-tooltip>
    <!-- table展示用户信息 -->
    <el-table style="margin: 10px 0" border :data="restaurantTableData">
      <el-table-column
          label="名称"
          align="center"
          prop="name"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="地址"
          align="center"
          prop="address"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="电话"
          align="center"
          prop="phone"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="描述"
          align="center"
          prop="description"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="状态"
          align="center"
          prop="status"
          show-overflow-tooltip
          :formatter="(row: any) => {
        const roleMap: Record<number, string> = { 1: '营业中', 2: '已打烊' };
        return roleMap[row.status] || '未知状态';
      }"
      ></el-table-column>
      <el-table-column label="操作" fixed="right" width="120px" align="center">
        <template #="{ row }">
          <el-tooltip effect="dark" content="编辑" placement="top">
            <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="handleEdit(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDelete(row.restaurantId)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="findAll"
        @size-change="handler"
    />
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer" size="1000px">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ restaurantForm.restaurantId ? "更新" : "添加" }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="restaurantForm" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input
              placeholder="请您输入名称"
              v-model="restaurantForm.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
              placeholder="请您输地址"
              v-model="restaurantForm.address"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
              placeholder="请您输入电话"
              v-model="restaurantForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="restaurantForm.status" placeholder="请选择状态">
            <el-option label="营业中" :value="1"></el-option>
            <el-option label="已打烊" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="content">
          <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
              style="border-bottom: 1px solid #ccc"
          />
          <Editor
              :defaultConfig="editorConfig"
              mode="default"
              v-model="restaurantForm.description"
              style="height: 400px; width: 600px; overflow-y: hidden"
              @onCreated="handleCreated"
              @onChange="handleChange"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>

</template>

<script setup lang="ts">
import {ref, reactive, onMounted, nextTick, shallowRef} from "vue";
import {ElFormItem, ElMessage, ElMessageBox} from "element-plus";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import {apiGet, apiPost} from "@/utils/api";
import {validateUtils} from "@/utils/validateUtils";
// 表单数据
let restaurantForm = reactive({
  restaurantId: 0,
  name: "",
  address: "",
  phone: "",
  description: "",
  status: 1,
});
//搜索表单数据
let queryForm = reactive({
  queryName: "",
  queryStatus: 0,
});
//默认页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(5);
//总个数
let total = ref<number>(0);
//存储全部用户的数组
let restaurantTableData = ref([]);
//定义响应式数据控制抽屉的显示与隐藏 添加用户和修改用户
let drawer = ref<boolean>(false);
//获取form组件实例
let formRef = ref<any>();
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      fieldName: "file",
      server: import.meta.env.VITE_SERVE + "upload/img",
      // 单个文件的最大体积限制，默认为 2M+
      maxFileSize: 10 * 1024 * 1024, // 10M
      onSuccess(file: any, res: any) {
        console.log("onSuccess", file, res);
      },
      // // 用户自定义插入图片
      customInsert(res: any, insertFn: any) {
        if (res.code === 200) {
          let url = res.msg;
          let alt = res.msg.slice(52);
          let href = res.msg;
          console.log("图片名称：" + alt);
          insertFn(url, alt, href);
        } else {
          ElMessage.error(res.msg);
        }
      },
    },
    uploadVideo: {
      server: import.meta.env.VITE_SERVE + "upload/img",
      fieldName: "file",

      // 单个文件的最大体积限制，默认为 10M
      maxFileSize: 100 * 1024 * 1024, // 100M
      // 超时时间，默认为 30 秒
      timeout: 15 * 1000, // 15 秒
      onSuccess(file: any, res: any) {
        console.log("onSuccess", file, res);
      },
      // // 用户自定义插入图片
      customInsert(res: any, insertFn: any) {
        if (res.code === 200) {
          let url = res.msg;
          let alt = res.msg.slice(52);
          let href = res.msg;
          console.log("视频名称：" + alt);
          insertFn(url);
        } else {
          ElMessage.error(res.msg);
        }
      },
    },
  },
};

// 编辑器创建完毕时的回调函数。
const handleCreated = (editor: any) => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};
//编辑器内容、选区变化时的回调函数。
const handleChange = (editor: any) => {
  restaurantForm.description = editor.getHtml();
};
//获取全部用户信息
let findAll = async (pager = 1) => {
  //收集当前页码
  pageNo.value = pager;
  let parameter = {
    page: pageNo.value,
    limit: pageSize.value,
    name: queryForm.queryName,
    status: queryForm.queryStatus,
  };
  //获取表单数据
  let {data} = await apiGet("/restaurant/findAll", parameter);
  total.value = data.count;
  restaurantTableData.value = data.data;
};

//分页器下拉菜单的自定义事件的回调
const handler = () => {
  findAll();
};

//搜索按钮的回调
const search = () => {
  findAll();
};

//添加用户按钮的回调
const handleAdd = () => {
  //抽屉显示出来
  drawer.value = true;
  //清空userParams的数据以及userParams继承User里面的所有数据
  Object.assign(restaurantForm, {
    restaurantId: 0,
    name: "",
    address: "",
    phone: "",
    status: 1,
    description: "",
  });
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

//更新用户按钮的回调
const handleEdit = (row: any) => {
  //抽屉显示出来
  drawer.value = true;
  //将用户的信息赋值给userParams
  Object.assign(restaurantForm, {
    ...row,
  });
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

//保存按钮的回调
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate();
  //保存按钮:添加新的用户|更新已有的用户账号信息
  restaurantForm.restaurantId
      ? await apiPost("/restaurant/edit", {...restaurantForm})
      : await apiPost("/restaurant/add", {...restaurantForm});
  await findAll();
  drawer.value = false;
};

//删除
const handleDelete = async (restaurantId: number) => {
  //提示用户确认删除吗
  ElMessageBox.confirm("此操作将永久删除该餐厅, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        await apiPost("/restaurant/delete", {restaurantId});
        await findAll(
            restaurantTableData.value.length > 1 ? pageNo.value : pageNo.value - 1,
        );
      })
      .catch(() => {
      });
};
const validatorName = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请输入名称"));
  } else {
    callback();
  }
};
const validateAddress = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请输入地址"));
  } else {
    callback();
  }
};
const validatorPhone = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请输入手机号"));
  } else if (!validateUtils.validatePhone(value)) {
    callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
};
//表单校验的规则对象
const rules = {
  name: [{required: true, trigger: "blur", validator: validatorName}],
  address: [{required: true, trigger: "blur", validator: validateAddress}],
  phone: [{required: true, trigger: "blur", validator: validatorPhone}],
};

//组件挂载完毕
onMounted(() => {
  findAll();
});
</script>

<style scoped></style>
